//
// Created by luosong on 15/8/26.
// Copyright (c) 2015 CHANJET. All rights reserved.
//

#import "CSPNetworkConfig.h"
#import "CSPNetworking.h"


@implementation CSPNetworkConfig {
    NSMutableArray *_urlFilters;
    NSMutableArray *_cacheDirPathFilters;
}

+ (instancetype)sharedInstance {
    static id sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}

- (id)init {
    self = [super init];
    if (self) {
        _urlFilters = [NSMutableArray array];
        _cacheDirPathFilters = [NSMutableArray array];
    }
    return self;
}

- (NSURL *)URL {
    // You can overwrite the URL by providing a full URL in URLString.
    NSURL *fullURL = [NSURL URLWithString:self.URLString];
    if ([fullURL.scheme isEqualToString:@"http"] || [fullURL.scheme isEqualToString:@"https"]) {
        NSMutableDictionary *headers = [self.headers mutableCopy];
        headers[@"Host"] = [fullURL host];
        self.headers = headers;
        return fullURL;
    }

    if (!self.URLString) {
        return self.baseURL;
    }

    return [NSURL URLWithString:self.URLString relativeToURL:self.baseURL];
}

- (void)addUrlFilter:(id<CSPUrlFilterProtocol>)filter {
    [_urlFilters addObject:filter];
}

- (void)addCacheDirPathFilter:(id<CSPCacheDirPathFilterProtocol>)filter {
    [_cacheDirPathFilters addObject:filter];
}

- (NSArray *)urlFilters {
    return [_urlFilters copy];
}

- (NSArray *)cacheDirPathFilters {
    return [_cacheDirPathFilters copy];
}

@end
